package fr.resasante.utils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.naming.NamingException;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import fr.resasante.exception.ApplicationException;

/**
 * Class for getting titles in XML
 * 
 * @author GEFFROY-DE-VILLEBLAN
 * 
 */
public final class WaysUtils {
	/**
	 * Class instance
	 */
	private static volatile WaysUtils instance = null;

	/**
	 * Root node
	 */
	private Element root;

	/**
	 * Constructor
	 */
	private WaysUtils() {
		super();
		loadXmlFile();
	}

	/**
	 * Method returning a Singleton class instance
	 * 
	 * @return Singleton instance
	 * @throws NamingException
	 */
	public final static WaysUtils getInstance() {
		if (WaysUtils.instance == null) {
			synchronized (WaysUtils.class) {
				if (WaysUtils.instance == null) {
					WaysUtils.instance = new WaysUtils();
				}
			}
		}
		return WaysUtils.instance;
	}

	/**
	 * Load the XML file
	 */
	private void loadXmlFile() {
		try {
			InputStream xmlStream = this.getClass().getClassLoader()
					.getResourceAsStream("ways.xml");
			SAXReader reader = new SAXReader();
			Document doc = reader.read(xmlStream);
			root = doc.getRootElement();
		} catch (Exception e) {
			throw new ApplicationException("Unable to find the XML file ways.xml", e);
		}
	}

	/**
	 * Get a list of ways
	 * 
	 * @return The list of ways
	 */
	public Map<String, String> getAllWays() {
		Map<String, String> ways = new HashMap<String, String>();
		@SuppressWarnings("rawtypes")
		Iterator iterator = root.elementIterator("way");
		while (iterator.hasNext()) {
			Element way = (Element) iterator.next();
			String abbr = way.elementText("abbr");
			String label = way.elementText("label");
			ways.put(abbr, label);
		}
		return ways;
	}
}